const User = require('../models/User');
const StudyProgress = require('../models/StudyProgress');
const CheckIn = require('../models/CheckIn');
const Resource = require('../models/Resource');
const { Op } = require('sequelize');

// 获取所有用户
const getAllUsers = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, search = '', role = '', status = '' } = req.query;
    
    const where = {};
    
    // 搜索条件
    if (search) {
      where[Op.or] = [
        { username: { [Op.like]: `%${search}%` } },
        { email: { [Op.like]: `%${search}%` } },
        { real_name: { [Op.like]: `%${search}%` } }
      ];
    }
    
    // 角色筛选
    if (role) {
      where.role = role;
    }
    
    // 状态筛选
    if (status) {
      where.status = status;
    }
    
    const users = await User.findAndCountAll({
      where,
      attributes: { exclude: ['password'] },
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize),
      order: [['createdAt', 'DESC']]
    });
    
    res.json({
      success: true,
      data: {
        users: users.rows,
        total: users.count,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        totalPages: Math.ceil(users.count / parseInt(pageSize))
      }
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户列表失败'
    });
  }
};

// 获取用户详情
const getUserDetail = async (req, res) => {
  try {
    const { id } = req.params;
    
    const user = await User.findByPk(id, {
      attributes: { exclude: ['password'] }
    });
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 获取用户学习统计
    const progress = await StudyProgress.findAll({
      where: { user_id: id }
    });
    
    const checkins = await CheckIn.findAll({
      where: { user_id: id },
      order: [['checkin_date', 'DESC']],
      limit: 10
    });
    
    res.json({
      success: true,
      data: {
        user,
        statistics: {
          totalProgress: progress.length,
          completedProgress: progress.filter(p => p.is_completed).length,
          totalCheckins: checkins.length,
          recentCheckins: checkins
        }
      }
    });
  } catch (error) {
    console.error('获取用户详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户详情失败'
    });
  }
};

// 更新用户信息
const updateUser = async (req, res) => {
  try {
    const { id } = req.params;
    const { username, email, real_name, role, status } = req.body;
    
    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    await user.update({
      username,
      email,
      real_name,
      role,
      status
    });
    
    res.json({
      success: true,
      message: '用户信息更新成功',
      data: {
        id: user.id,
        username: user.username,
        email: user.email,
        real_name: user.real_name,
        role: user.role,
        status: user.status
      }
    });
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.status(500).json({
      success: false,
      message: '更新用户信息失败'
    });
  }
};

// 删除用户
const deleteUser = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 不能删除自己
    if (parseInt(id) === req.user.id) {
      return res.status(400).json({
        success: false,
        message: '不能删除自己的账户'
      });
    }
    
    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 删除用户相关数据
    await StudyProgress.destroy({ where: { user_id: id } });
    await CheckIn.destroy({ where: { user_id: id } });
    await user.destroy();
    
    res.json({
      success: true,
      message: '用户删除成功'
    });
  } catch (error) {
    console.error('删除用户失败:', error);
    res.status(500).json({
      success: false,
      message: '删除用户失败'
    });
  }
};

// 更新用户状态
const updateUserStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    
    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    await user.update({ status });
    
    res.json({
      success: true,
      message: '用户状态更新成功'
    });
  } catch (error) {
    console.error('更新用户状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新用户状态失败'
    });
  }
};

// 获取概览统计
const getOverviewStats = async (req, res) => {
  try {
    // 用户统计
    const totalUsers = await User.count();
    const activeUsers = await User.count({ where: { status: 'active' } });
    const todayRegistrations = await User.count({
      where: {
        createdAt: {
          [Op.gte]: new Date(new Date().setHours(0, 0, 0, 0))
        }
      }
    });
    
    // 学习统计
    const totalProgress = await StudyProgress.count();
    const completedProgress = await StudyProgress.count({ where: { is_completed: true } });
    
    // 打卡统计
    const totalCheckins = await CheckIn.count();
    const todayCheckins = await CheckIn.count({
      where: {
        checkin_date: new Date().toISOString().split('T')[0]
      }
    });
    
    // 资源统计
    const totalResources = await Resource.count();
    
    res.json({
      success: true,
      data: {
        users: {
          total: totalUsers,
          active: activeUsers,
          todayRegistrations
        },
        progress: {
          total: totalProgress,
          completed: completedProgress,
          completionRate: totalProgress > 0 ? (completedProgress / totalProgress * 100).toFixed(1) : 0
        },
        checkins: {
          total: totalCheckins,
          today: todayCheckins
        },
        resources: {
          total: totalResources
        }
      }
    });
  } catch (error) {
    console.error('获取概览统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取概览统计失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// 获取用户统计
const getUsersStats = async (req, res) => {
  try {
    // 按角色统计
    const roleStats = await User.findAll({
      attributes: [
        'role',
        [User.sequelize.fn('COUNT', User.sequelize.col('role')), 'count']
      ],
      group: ['role']
    });
    
    // 按状态统计
    const statusStats = await User.findAll({
      attributes: [
        'status',
        [User.sequelize.fn('COUNT', User.sequelize.col('status')), 'count']
      ],
      group: ['status']
    });
    
    // 注册趋势（最近7天）
    const registrationTrend = await User.findAll({
      attributes: [
        [User.sequelize.fn('DATE', User.sequelize.col('createdAt')), 'date'],
        [User.sequelize.fn('COUNT', User.sequelize.col('id')), 'count']
      ],
      where: {
        createdAt: {
          [Op.gte]: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
        }
      },
      group: [User.sequelize.fn('DATE', User.sequelize.col('createdAt'))],
      order: [[User.sequelize.fn('DATE', User.sequelize.col('createdAt')), 'ASC']]
    });
    
    res.json({
      success: true,
      data: {
        roleStats,
        statusStats,
        registrationTrend
      }
    });
  } catch (error) {
    console.error('获取用户统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户统计失败'
    });
  }
};

// 获取学习进度统计
const getProgressStats = async (req, res) => {
  try {
    // 整体进度完成情况
    const progressOverview = await StudyProgress.findAll({
      attributes: [
        'day_number',
        [StudyProgress.sequelize.fn('COUNT', StudyProgress.sequelize.col('*')), 'totalUsers'],
        [StudyProgress.sequelize.fn('SUM', StudyProgress.sequelize.literal('CASE WHEN is_completed = true THEN 1 ELSE 0 END')), 'completedUsers']
      ],
      group: ['day_number'],
      order: [['day_number', 'ASC']]
    });
    
    // 用户学习进度排行
    const userProgressRanking = await StudyProgress.findAll({
      attributes: [
        'user_id',
        [StudyProgress.sequelize.fn('COUNT', StudyProgress.sequelize.col('*')), 'totalTasks'],
        [StudyProgress.sequelize.fn('SUM', StudyProgress.sequelize.literal('CASE WHEN is_completed = true THEN 1 ELSE 0 END')), 'completedTasks']
      ],
      include: [{
        model: User,
        attributes: ['username', 'real_name']
      }],
      group: ['user_id', 'User.id'],
      order: [[StudyProgress.sequelize.fn('SUM', StudyProgress.sequelize.literal('CASE WHEN is_completed = true THEN 1 ELSE 0 END')), 'DESC']],
      limit: 10
    });
    
    res.json({
      success: true,
      data: {
        progressOverview,
        userProgressRanking
      }
    });
  } catch (error) {
    console.error('获取学习进度统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取学习进度统计失败'
    });
  }
};

// 获取打卡统计
const getCheckinStats = async (req, res) => {
  try {
    // 打卡趋势（最近30天）
    const checkinTrend = await CheckIn.findAll({
      attributes: [
        'checkin_date',
        [CheckIn.sequelize.fn('COUNT', CheckIn.sequelize.col('*')), 'count']
      ],
      where: {
        checkin_date: {
          [Op.gte]: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
        }
      },
      group: ['checkin_date'],
      order: [['checkin_date', 'ASC']]
    });
    
    // 连续打卡排行
    const continuousCheckinRanking = await User.findAll({
      attributes: ['id', 'username', 'real_name', 'continuous_checkin_days'],
      where: {
        continuous_checkin_days: { [Op.gt]: 0 }
      },
      order: [['continuous_checkin_days', 'DESC']],
      limit: 10
    });
    
    res.json({
      success: true,
      data: {
        checkinTrend,
        continuousCheckinRanking
      }
    });
  } catch (error) {
    console.error('获取打卡统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取打卡统计失败'
    });
  }
};

// 获取所有资源（管理员视图）
const getAllResources = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, search = '', category = '' } = req.query;
    
    const where = {};
    
    if (search) {
      where[Op.or] = [
        { title: { [Op.like]: `%${search}%` } },
        { description: { [Op.like]: `%${search}%` } }
      ];
    }
    
    if (category) {
      where.category = category;
    }
    
    const resources = await Resource.findAndCountAll({
      where,
      include: [{
        model: User,
        as: 'creator',
        attributes: ['username', 'real_name']
      }],
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize),
      order: [['createdAt', 'DESC']]
    });
    
    res.json({
      success: true,
      data: {
        resources: resources.rows,
        total: resources.count,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        totalPages: Math.ceil(resources.count / parseInt(pageSize))
      }
    });
  } catch (error) {
    console.error('获取资源列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取资源列表失败'
    });
  }
};

// 创建资源
const createResource = async (req, res) => {
  try {
    const { title, description, url, category, difficulty } = req.body;
    
    const resource = await Resource.create({
      title,
      description,
      url,
      category,
      difficulty,
      created_by: req.user.id
    });
    
    res.status(201).json({
      success: true,
      message: '资源创建成功',
      data: resource
    });
  } catch (error) {
    console.error('创建资源失败:', error);
    res.status(500).json({
      success: false,
      message: '创建资源失败'
    });
  }
};

// 更新资源
const updateResource = async (req, res) => {
  try {
    const { id } = req.params;
    const { title, description, url, category, difficulty } = req.body;
    
    const resource = await Resource.findByPk(id);
    if (!resource) {
      return res.status(404).json({
        success: false,
        message: '资源不存在'
      });
    }
    
    await resource.update({
      title,
      description,
      url,
      category,
      difficulty
    });
    
    res.json({
      success: true,
      message: '资源更新成功',
      data: resource
    });
  } catch (error) {
    console.error('更新资源失败:', error);
    res.status(500).json({
      success: false,
      message: '更新资源失败'
    });
  }
};

// 删除资源
const deleteResource = async (req, res) => {
  try {
    const { id } = req.params;
    
    const resource = await Resource.findByPk(id);
    if (!resource) {
      return res.status(404).json({
        success: false,
        message: '资源不存在'
      });
    }
    
    await resource.destroy();
    
    res.json({
      success: true,
      message: '资源删除成功'
    });
  } catch (error) {
    console.error('删除资源失败:', error);
    res.status(500).json({
      success: false,
      message: '删除资源失败'
    });
  }
};

// 导出用户数据
const exportUsers = async (req, res) => {
  try {
    const users = await User.findAll({
      attributes: { exclude: ['password'] },
      order: [['createdAt', 'DESC']]
    });
    
    res.json({
      success: true,
      data: users
    });
  } catch (error) {
    console.error('导出用户数据失败:', error);
    res.status(500).json({
      success: false,
      message: '导出用户数据失败'
    });
  }
};

// 导出学习进度数据
const exportProgress = async (req, res) => {
  try {
    const progress = await StudyProgress.findAll({
      include: [{
        model: User,
        attributes: ['username', 'real_name']
      }],
      order: [['createdAt', 'DESC']]
    });
    
    res.json({
      success: true,
      data: progress
    });
  } catch (error) {
    console.error('导出学习进度数据失败:', error);
    res.status(500).json({
      success: false,
      message: '导出学习进度数据失败'
    });
  }
};

module.exports = {
  getAllUsers,
  getUserDetail,
  updateUser,
  deleteUser,
  updateUserStatus,
  getOverviewStats,
  getUsersStats,
  getProgressStats,
  getCheckinStats,
  getAllResources,
  createResource,
  updateResource,
  deleteResource,
  exportUsers,
  exportProgress
}; 